package com.bml.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.bml.es.domain.EsProduct;
import com.bml.es.service.ProductService;
import com.bml.es.vo.ESRequestParam;
import com.bml.es.vo.ESResponseResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {

    @Qualifier("restHighLevelClient")
    @Autowired
    private RestHighLevelClient client;

    private final String INDEX_NAME = "product_db";

    public static final Integer PAGE_SIZE = 10;

    @Override
    public ESResponseResult search(ESRequestParam param) {
        ESResponseResult result = null;
        //1.构建查询条件请求
        SearchRequest requestBuilder = buildSearchRequest(param);
        try {
            SearchResponse response = client.search(requestBuilder, RequestOptions.DEFAULT);
            System.out.println("response=" + response);
            //3、分析响应数据，封装成指定的格式
            result = buildSearchResponse(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private ESResponseResult buildSearchResponse(SearchResponse response, ESRequestParam param) {
        ESResponseResult result = new ESResponseResult();
        SearchHits hits = response.getHits();
        List<EsProduct> esProducts = new ArrayList<>();
        //获取产品信息
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                EsProduct esModel = JSON.parseObject(sourceAsString, EsProduct.class);
                //判断是否按关键字检索，若是就显示高亮，否则不显示
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    //如果是通过关键字检索的，获取高亮 拿到高亮信息显示标题
                    HighlightField field = hit.getHighlightFields().get("name");
                    //判断name中是否含有查询的关键字(因为是多字段查询，因此可能不包含指定的关键字，假设不包含则显示原始name字段的信息)
                    String highName = field != null ? field.getFragments()[0].toString() : esModel.getName();
                    esModel.setName(highName);
                }
                esProducts.add(esModel);
            }
        }
        result.setProducts(esProducts);
        //当前商品涉及到的所有品牌信息，小米手机和小米电脑都属于小米品牌，过滤重复品牌信息
        List<ESResponseResult.BrandVo> brandVoList = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {

            ESResponseResult.BrandVo brandVo = new ESResponseResult.BrandVo();
            //品牌ID
            long brandId = bucket.getKeyAsNumber().longValue();
            //获取品牌的名字
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            //获取品牌的图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            brandVo.setBrandId(brandId);
            brandVo.setBrandImg(brandImgAgg.getBuckets().get(0).getKeyAsString());
            brandVo.setBrandName(brandNameAgg.getBuckets().get(0).getKeyAsString());
            brandVoList.add(brandVo);
        }
        result.setBrands(brandVoList);
        //分类信息
        List<ESResponseResult.CategoryVo> categoryVos = new ArrayList<>();
        ParsedLongTerms categoryAgg = response.getAggregations().get("category_agg");
        for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
            ESResponseResult.CategoryVo categoryVo = new ESResponseResult.CategoryVo();
            //获取分类ID
            long categoryId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms categoryNameAgg = bucket.getAggregations().get("category_name_agg");
            categoryVo.setCategoryId(categoryId);
            categoryVo.setCategoryName(categoryNameAgg.getBuckets().get(0).getKeyAsString());
            categoryVos.add(categoryVo);
        }

        result.setCategorys(categoryVos);
        //属性信息

        //5、获取商品相关的所有属性信息
        List<ESResponseResult.AttrVo> attrVos = new ArrayList<>();
        //获取属性信息的聚合
        ParsedNested attrsAgg = response.getAggregations().get("attrs_agg");
        ParsedLongTerms attrIdAgg = attrsAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            ESResponseResult.AttrVo attrVo = new ESResponseResult.AttrVo();
            //获取属性ID值
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            //获取属性的名字
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);

            //获取属性的值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            System.out.println("===1==="+attrValueAgg.getBuckets());

            for (Terms.Bucket b : attrValueAgg.getBuckets()) {
                String bb = b.getKeyAsString();
                System.out.println("bb:"+bb);
            }

            List<String> attrValues = attrValueAgg.getBuckets().stream().map(item -> item.getKeyAsString()).collect(Collectors.toList());
            attrVo.setAttrValue(attrValues);
            System.out.println("===2==="+attrValues);
            attrVos.add(attrVo);
        }

        result.setAttrs(attrVos);

        //设置分页
        result.setPageNum(param.getPageNum());
        long total = hits.getTotalHits().value;
        //获取总记录数
        result.setTotal(total);

        double pages = Math.ceil(total / PAGE_SIZE);
        result.setTotalPages((int) pages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= pages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        return result;
    }

    private SearchRequest buildSearchRequest(ESRequestParam param) {

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //构建关键字查询
        if (!StringUtils.isEmpty(param.getKeyword())) {
            //单字段查询
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", param.getKeyword()));
            //多字段查询
            // boolQueryBuilder.must(QueryBuilders.multiMatchQuery(param.getKeyword(),"name","keywords","subTitle"));
        }

        //根据品牌ID查询
        List<Long> brandId = param.getBrandId();
        if (brandId != null && !brandId.isEmpty()) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brandId", brandId));
        }

        //根据类目ID进行过滤
        Long categoryId = param.getCategoryId();
        if (categoryId != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("categoryId", categoryId));
        }

        //根据属性进行过滤 attrs=1_白色:黑色&2_4核

        List<String> attrs = param.getAttrs();
        if (attrs != null && !attrs.isEmpty()) {
            attrs.forEach(item -> {
                String[] split = item.split("\\_");
                String attrId = split[0];
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                // String attrValues[] = split[1].split("\\:");
                boolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                boolQuery.must(QueryBuilders.termQuery("attrs.attrValue", split[1]));
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", boolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            });
        }


        //构建过滤条件：是否有货，价格区间
        if (null != param.getHasStock()) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        //价格区间
        String price = param.getPrice();
        if (!StringUtils.isEmpty(price)) {
            String[] split = price.split("\\_");
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price");
            if (split.length == 2) {
                rangeQueryBuilder.gte(split[0]).lte(split[1]);
            } else if (split.length == 1) {
                String p = split[0];
                if (p.startsWith("_")) {
                    rangeQueryBuilder.lte(p);
                }
                if (p.endsWith("_")) {
                    rangeQueryBuilder.gte(p);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }

        sourceBuilder.query(boolQueryBuilder);
        //实现排序、高亮、分页操作

        //排序 传入的参数值形式 sort=price_asc/desc

        String sort = param.getSort();
        if (!StringUtils.isEmpty(sort)) {

            String[] split = sort.split("\\_");
            SortOrder order = split[1].equals("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(split[0], order);
        }

        //高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        //分页
        sourceBuilder.from((param.getPageNum() - 1) * PAGE_SIZE);
        sourceBuilder.size(PAGE_SIZE);

        /**
         * 对品牌、分类信息、属性信息进行聚合分析
         */


        //品牌
        //聚合品牌ID
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(10);
        //通过品牌ID聚合继续自聚合到品牌名称和品牌图片
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        //分类信息聚合
        TermsAggregationBuilder category_agg = AggregationBuilders.terms("category_agg");
        category_agg.field("categoryId").size(10);
        category_agg.subAggregation(AggregationBuilders.terms("category_name_agg").field("categoryName").size(1));
        sourceBuilder.aggregation(category_agg);

        //对属性进行聚合

        NestedAggregationBuilder nested = AggregationBuilders.nested("attrs_agg", "attrs");
        //按照属性ID进行聚合
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        nested.subAggregation(attr_id_agg);
        //对属性名称进行子聚合
        TermsAggregationBuilder attr_name_agg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName");
        attr_id_agg.subAggregation(attr_name_agg);
        //对属性值进行子聚合
        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue");
        attr_id_agg.subAggregation(attr_value_agg);
        sourceBuilder.aggregation(nested);


        System.out.println("构建的DSL语句 {}:" + sourceBuilder.toString());        //返回构建好的查询条件request
        SearchRequest request = new SearchRequest(new String[]{INDEX_NAME}, sourceBuilder);
        return request;
    }


    public static void main(String[] args) {
        int pagesize = 10;
        int total = 200;
        System.out.println(Math.ceil(total / pagesize));
    }
}
